package cn.itsource.wechat.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.itsource.basic.other.exception.BusinessException;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.LoginInfo;
import cn.itsource.org.domain.User;
import cn.itsource.org.mapper.UserMapper;
import cn.itsource.wechat.domain.*;
import cn.itsource.wechat.mapper.WxUserMapper;
import cn.itsource.wechat.service.IWeChatService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public class WeChatServiceImpl implements IWeChatService {


    @Autowired
    private WechartProperties wechartProperties;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisService redisService;

    @Override
    public String callback(String code) {

        //通过微信回调得到的code拿到token
        WechatTokenDto tokenObj = getWechatTokenDto(code);

        //根据获取到的token去拿到微信用户信息
        WechartUserInfoDto curUser = getWechartUserInfoDto(tokenObj);

        //如果在wxuser表不存在
        WxUser wxUser = wxUserMapper.selectOneByOpenId(tokenObj.getOpenid());
        if (wxUser == null) {
            //如果微信表里面没有这个用户就添加
            wxUser = copyWxUser(curUser);
            wxUserMapper.insertSelective(wxUser);
            //添加完成之后跳转到绑定手机号页面
        } else if (wxUser.getUser_id() != null) {
            //如果没有绑定对应用户
            User user = userMapper.selectByPrimaryKey(wxUser.getUser_id());
            //如果在wxUser表里面存在在User表里面不存在 并且 绑定手机号
            if (user != null && StringUtils.isNotBlank(user.getPhone())) {

                LoginInfo loginInfo = BeanUtil.copyProperties(user, LoginInfo.class);
                String token = IdUtil.fastSimpleUUID();
                loginInfo.setToken(token);

                redisService.setStringKeyAndValue(token, loginInfo, 30);
                //跳转到首页
                return "redirect:http://bugtracker.itsource.cn:8081/index.html?token=" + token
                        + "&username=" + StringUtils.defaultIfBlank(user.getUsername(), "")
                        + "&email=" + StringUtils.defaultIfBlank(user.getEmail(), "")
                        + "&phone=" + StringUtils.defaultIfBlank(user.getPhone(), "");
            }
        }
        return "redirect:http://bugtracker.itsource.cn:8081/binder.html?openid=" + curUser.getOpenid();
    }

    @Override
    public LoginInfo binder(BinderDto binderDto) {
        String code = redisService.getKeyStringValue(binderDto.getPhone());
        if (!StringUtils.equalsIgnoreCase(binderDto.getCode(), code)) {
            throw new BusinessException("验证码已过期!");
        }

        //根据手机号查询到用户
        User user = userMapper.selectOneByPhone(binderDto.getPhone());
        if (user == null) {
            user = new User();
            user.setPhone(binderDto.getPhone());
            user.setPassword("123");
            user.init();
            userMapper.insertSelective(user);
        }

        //根据OpenId拿到wxUser对象
        WxUser wxUser = wxUserMapper.selectOneByOpenId(binderDto.getOpenid());
        wxUser.setUser_id(user.getId());
        //将User和WxUser进行关联
        wxUserMapper.updateByPrimaryKeySelective(wxUser);

        LoginInfo loginInfo = BeanUtil.copyProperties(user, LoginInfo.class);
        String token = IdUtil.fastSimpleUUID();
        loginInfo.setToken(token);

        redisService.setStringKeyAndValue(token, loginInfo, 30);
        return loginInfo;
    }

    private WechartUserInfoDto getWechartUserInfoDto(WechatTokenDto tokenObj) {
        String getUserUrl = String.format(wechartProperties.getUserinfoUrl(), tokenObj.getAccess_token(), tokenObj.getOpenid());
        String curUserJson = HttpUtil.get(getUserUrl);
        //拿到微信用户信息
        return JSONObject.parseObject(curUserJson, WechartUserInfoDto.class);
    }

    private WechatTokenDto getWechatTokenDto(String code) {
        String getTokeUrl = String.format(wechartProperties.getTokenUrl(), wechartProperties.getAppId(), wechartProperties.getAppSecrect(), code);
        String tokenJson = HttpUtil.get(getTokeUrl);
        return JSONObject.parseObject(tokenJson, WechatTokenDto.class);
    }

    private WxUser copyWxUser(WechartUserInfoDto curUser) {
        WxUser wxUser = new WxUser();
        wxUser.setOpenid(curUser.getOpenid());
        wxUser.setAddress(curUser.getCountry() + curUser.getProvince() + curUser.getCity());
        wxUser.setHeadimgurl(curUser.getHeadimgurl().replace("\\", ""));
        wxUser.setNickname(curUser.getNickname());
        wxUser.setUnionid(curUser.getUnionid());
        return wxUser;
    }
}
